package com.wanlian.service.impl;

import com.wanlian.common.*;
import com.wanlian.dao.*;
import com.wanlian.entity.*;
import com.wanlian.model.ResultModel;
import com.wanlian.service.UserScoreServices;
import com.wanlian.util.DateUtil;
import com.wanlian.util.HttpUtils;
import com.wanlian.util.StringUtil;
import com.wanlian.vo.Page;
import com.wanlian.vo.ScoreHistoryVo;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserScoreServicesImpl implements UserScoreServices {

    @Autowired
    private UserScoreDao userScoreDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ScoreHistoryDao scoreHistoryDao;
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private TaskDao taskDao;
    @Autowired
    private WordBookDao wordBookDao;
    @Autowired
    private IntDetailDao intDetailDao;


    @Override
    public ResultModel queryUserScoreByParam(PageCondition pageCondition, int uid) {
        return userScoreDao.queryUserScoreByParams(pageCondition, uid);
    }

/*
    @Override
    public ResultModel queryUserScoreHistoryByParam(PageCondition pageCondition) {
        return userScoreDao.queryUserScoreHistoryByParams(pageCondition);
    }
*/

    @Override
    public ResultModel queryUserScoreHistoryByParam(PageCondition pageCondition, int uid) {
        return userScoreDao.queryUserScoreHistoryByParams(pageCondition, uid);
    }

//    /**
//     * 查询用户昨日积分
//     *
//     * @param userId
//     * @return
//     */
//    @Override
//    public UserScore queryUserScoreYes(int userId) {
//        try {
//            Date dateNow = DateUtil.currentDate();
//            Date dateStart = DateUtil.addDay(DateUtil.currentDate(), -1);
//            String startDate = DateUtil.formatDateNoHour(dateStart);
//            String endDate = DateUtil.formatDateNoHour(dateNow);
//            String hql = String.format("from %s where userId=? and ( addTime between ? and ?)", entityClassName());
//            UserScore score = this.queryForObject(hql, new Object[]{userId, startDate, endDate});
//            return score;
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 查询用户昨日积分
     *
     * @param userId
     * @return
     */
    @Override
    public ResultModel queryUserScoreYes(int userId) {
        UserScore score = new UserScore();
        List<ScoreHistory> scoreHistories = this.scoreHistoryDao.queryHistoryByYesAndUserId(userId);
        double Score = 0;
        double iscore = 0;
        double dscore = 0;
        if (scoreHistories.size() == 0) {
            return new ResultModel(false, null, "昨日未产生任何积分");
        } else {
            //ScoreHistoryVo vo = new ScoreHistoryVo();
            for (ScoreHistory item : scoreHistories) {
                Score += item.getScore();
                if (item.getTrantype() == 5 || item.getTrantype() == 2) {
                    iscore += item.getScore();
                } else {
                    iscore += item.getIscore();
                    dscore += item.getDscore();
                   // vo.setScoreHistory(item);
                }
            }
            score.setUserId(userId);
            score.setScore(Score);
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("score", score.getScore() + "");
        //昨日获取总积分
        double rscore = score.getScore();
        //0.01
        WordBook intPor_wordBook = wordBookDao.queryWordBookByVal2("intnum_proportion");
        float intPor = Float.parseFloat(intPor_wordBook.getWbval1());
        //0.01
        WordBook dxPor_wordBook = wordBookDao.queryWordBookByVal2("dxnum_proportion");
        float dxPor = Float.parseFloat(dxPor_wordBook.getWbval1());

        //一个int--rmb
        float intR = IntRmb.intRmb();

        float rmb = IntRmb.rounding((float) (dscore * dxPor + iscore * intPor * intR));


        map.put("rmb", rmb + "");
        return new ResultModel(true, map);
    }

    /**
     * 查询用户昨日积分明细
     *
     * @param userId
     * @return
     */
    @Override
    public ResultModel queryUserScoreYesItem(Page page, int userId) {
        List<ScoreHistoryVo> vos = new ArrayList();
        ResultModel resultModel = this.scoreHistoryDao.queryHistoryByUserId(page, userId);
        if (resultModel.getCount() == 0) {
            return resultModel;
        } else {
            ScoreHistoryVo vo = new ScoreHistoryVo();
            List<ScoreHistory> histories = (List<ScoreHistory>) resultModel.getObject();
            for (ScoreHistory item : histories) {
                if (StringUtil.hasValue(item.getDeviceId())) {
                    Device device = this.deviceDao.queryByDeviceId(item.getDeviceId());
                    vo.setDevice(device);
                }
                if (item.getTaskId() != 0) {
                    Task task = this.taskDao.queryById(item.getId());
                    vo.setTask(task);
                }
                vo.setScoreHistory(item);
                vos.add(vo);
            }
            resultModel.setObject(vos);
        }
        return resultModel;
    }

    @Override
    public ResultModel queryUserScoreWater(PageCondition pageCondition, int uid) {
        return userScoreDao.queryUserScoreWater(pageCondition, uid);
    }


    @Override
    public ResultModel queryUserScoreOrder(PageCondition pageCondition) {
        return userScoreDao.queryUserScoreOrder(pageCondition);
    }

    @Override
    public ResultModel queryUserSumScoreOrder(PageCondition pageCondition) {
        return userScoreDao.queryUserSumScoreOrder(pageCondition);
    }


    @Override
    public ResultModel doUpdateInt(IntChange intChange, int userId) {
        ResultModel resultModel = new ResultModel();
        double intNum = intChange.getNum();
        //查询是否为工作日
        try {
            if (IsHoliday.isHoliday()) {
                resultModel.setMessage("请于工作日9:00-16:00兑换");
                resultModel.setBresult(false);
                return resultModel;
            }
        } catch (ParseException e) {
            System.out.println(e);
        }
        //查询当天是否兑换
//        long num = scoreHistoryDao.queryChangeIntToday(userId);
//        if (num > 0) {
//            resultModel.setMessage("今日兑换次数已用完，请于第二个工作日9:00~16:00进行兑换");
//            resultModel.setBresult(false);
//            return resultModel;
//        }
        //查询用户int积分
        UserScore userScore = userScoreDao.queryUserScoreByParams(userId, RankType.RANK_INT);
        //查询用户信息
        User user = userDao.queryById(userId);
        //以太坊钱包格式验证 1.0x开头,2.40位16进制
        String intAccount = user.getIntAccount();
        if(!StringUtil.hasValue(intAccount)){
            return new ResultModel(false,"请先绑定int钱包地址");
        }
        WordBook cgt_wordBook = wordBookDao.queryWordBookByVal2("intcgtype");
        /** 现备两种提现方案，在INT主链上线，稳定可用的条件下用方案一，否则用方案二。*/
        int flag = Integer.parseInt(cgt_wordBook.getWbval1());
        /**方案一、可兑换INT积分兑换成INT提现到INT钱包，10000个积分起兑换，每次兑换需扣掉汽油费。一天限兑换1次*/
        //fee为汽油费
        WordBook tip_wordBook = wordBookDao.queryWordBookByVal2("tip");
        float fee = Float.parseFloat(tip_wordBook.getWbval1());

        WordBook score_wordBook = wordBookDao.queryWordBookByVal2("intnum_proportion");
        float scorenum = (float) intNum / Float.parseFloat(score_wordBook.getWbval1());
        if (userScore.getScore() < scorenum) {
            resultModel.setMessage("积分不足，请赚取积分！");
            resultModel.setBresult(false);
            return resultModel;
        }
        int cnum = 100;
      /*  if (flag == 1) {
            cnum = 100;
        }
        if (flag == 2) {
            cnum = 300;
        }*/
//        if (intNum < cnum) {
//            resultModel.setMessage(cnum + "个起兑换");
//            resultModel.setBresult(false);
//            return resultModel;
//        } else {
            //减去用户int积分
            userScore.setScore(userScore.getScore() - scorenum);
            //添加积分纪录
            ScoreHistory scoreHistory = new ScoreHistory();
            scoreHistory.setUserId(userId);
            scoreHistory.setAddTime(DateUtil.currentTimestamp());
            scoreHistory.setRankType(RankType.RANK_INT);
            scoreHistory.setScore(-scorenum);
            scoreHistory.setIntnum(intNum);
            scoreHistory.setTrantype(ConstantCode.TRANS_INTEXT);
            scoreHistoryDao.add(scoreHistory);
            //添加至int兑换详情表
            IntChangeDetail intChangeDetail = new IntChangeDetail();
            intChangeDetail.setShid(scoreHistory.getId());
            intChangeDetail.setWallet(user.getIntAccount());
            intChangeDetail.setIntnum(intNum);
            intChangeDetail.setRealarrival(intNum - fee);
            intChangeDetail.setGas(fee);
            intChangeDetail.setEthtx(null);
            intChangeDetail.setPicktime(DateUtil.currentTimestamp());
            intChangeDetail.setStatus(ConstantCode.STATUS_SUBMIT);
            intDetailDao.add(intChangeDetail);
            resultModel.setBresult(true);
            resultModel.setMessage("已提交");
            return resultModel;
//        }
    }


}
